<script setup>
import { onMounted, ref, watch } from 'vue'
import * as echarts from 'echarts'
import { energyType, topologymenu, topologyTree, getContrast } from '@/api/test'

// 获取类别

const dataL = ref({
  firstOrder: [],
  secondLevel: [],
  treeVal: []
})

const activeF = ref(0)
const firstClick = (id) => {
  activeF.value = id
  getTopologyTree()
}
const activeS = ref(0)
const secondClick = (id) => {
  activeS.value = id
  getTopologyTree()
}

const treeRef = ref()
const treeId = ref(0)
const defaultProps = {
  children: 'children',
  label: 'name'
}
const handleNodeClick = (data) => {
  treeId.value = data.id
}
const filterText = ref('')
watch(filterText, (val) => {
  treeRef.value.filter(val)
})
const filterNode = (value, data) => {
  if (!value) return true
  return data.name.includes(value)
}

// 右侧表单
const getTodayFormatted = () => {
  const today = new Date()
  const year = today.getFullYear()
  const month = String(today.getMonth() + 1).padStart(2, '0')
  const day = String(today.getDate()).padStart(2, '0')
  const hours = '00'
  const minutes = '00'
  const seconds = '00'
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}
const formInline = ref({
  startTime: '',
  endTime: ''
})
const dateType = ref('daterange')
const typeChart = ref(0)
const changeType = (type) => {
  dateType.value = type
}
const changeTypeChart = (type) => {
  typeChart.value = type
}
function formatDateToStartOfDay(date) {
  if (typeof date === 'string') {
    date = new Date(date)
    if (isNaN(date.getTime())) {
      throw new Error('Invalid date string')
    }
  }
  if (!(date instanceof Date)) {
    throw new Error('Invalid date')
  }
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day} 00:00:00`
}
function adjustDateByTypeFinal(dateStr, type) {
  const date = new Date(dateStr.replace(' ', 'T'))
  if (isNaN(date.getTime())) throw new Error('Invalid date string')
  if (type === 0) {
    date.setMonth(date.getMonth() - 1)
  } else {
    date.setFullYear(date.getFullYear() - 1)
  }
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} 00:00:00`
}
const onSubmit = () => {
  const fData = formatDateToStartOfDay(formInline.value.startTime[0])
  const sData = formatDateToStartOfDay(formInline.value.startTime[1])
  const fData2 = adjustDateByTypeFinal(fData, typeChart.value)
  const sData2 = adjustDateByTypeFinal(sData, typeChart.value)
  const isTong = typeChart.value === 0 ? 'tong' : 'huan'
  const dateTypeType =
    dateType.value === 'daterange' ? 'day' : dateType.value === 'monthrange' ? 'day' : 'month'
  const data = {
    treeNodeId: treeId.value,
    beginCollectTime: fData,
    endCollectTime: sData,
    type: isTong,
    name: dateTypeType,
    energyType: 1,
    ont: 'y',
    time: 'time',
    beginCollectTime1: fData2,
    endCollectTime1: sData2
  }
  getContrastFun(data)
}
//echarts图表
const changeNum = (percentStr) => {
  let value = parseFloat(percentStr.replace('%', ''))
  let formattedValue = value.toFixed(2)
  return formattedValue
}
const myChart = ref(null)
const changeEchartsFun = (data, type) => {
  let timeList = []
  let thisEnergyList = []
  let lastEnergyList = []
  let compareList = []
  data.forEach((item) => {
    timeList.push(item.time)
    thisEnergyList.push(item.thisEnergy)
    lastEnergyList.push(item.lastEnergy)
    const num = changeNum(item.compare)
    compareList.push(num)
  })
  const typeName = type === 0 ? '同比' : '环比'
  if (myChart.value) {
    myChart.value.setOption({
      xAxis: {
        data: timeList
      },
      yAxis: [
        {
          type: 'value',
          name: '',
          min: 0,
          max: 120000,
          axisLabel: {
            formatter: '{value}'
          }
        },
        {
          type: 'value',
          name: typeName,
          min: -400,
          max: 800,
          axisLabel: {
            formatter: '{value}%'
          }
        }
      ],
      series: [
        {
          data: thisEnergyList
        },
        {
          data: lastEnergyList
        },
        {
          data: compareList
        }
      ]
    })
  }
}

const setUpEcharts = (data = [], type = 0) => {
  let timeList = []
  let thisEnergyList = []
  let lastEnergyList = []
  let compareList = []
  if (data) {
    data.forEach((item) => {
      timeList.push(item.time)
      thisEnergyList.push(item.thisEnergy)
      lastEnergyList.push(item.lastEnergy)
      const num = changeNum(item.compare)
      compareList.push(num)
    })
  }
  const typeName = type === 0 ? '同比' : '环比'
  const chartDom = document.querySelector('.mainE')
  myChart.value = echarts.init(chartDom)
  const option = {
    color: [
      '#5470c6',
      '#91cc75',
      '#ee6666',
      '#ee6666',
      '#73c0de',
      '#3ba272',
      '#fc8452',
      '#9a60b4',
      '#ea7ccc'
    ],
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        crossStyle: {
          color: '#999'
        }
      }
    },
    toolbox: {
      feature: {
        dataView: { show: false, readOnly: false },
        magicType: { show: false, type: ['line', 'bar'] },
        restore: { show: false },
        saveAsImage: { show: false }
      }
    },
    legend: {
      data: ['本期', '同期', '同比'],
      left: '30'
    },
    xAxis: [
      {
        type: 'category',
        data: timeList,
        axisPointer: {
          type: 'shadow'
        }
      }
    ],
    yAxis: [
      {
        type: 'value',
        name: '',
        min: 0,
        max: 120000,
        axisLabel: {
          formatter: '{value}'
        }
      },
      {
        type: 'value',
        name: typeName,
        min: -400,
        max: 800,
        axisLabel: {
          formatter: '{value}%'
        }
      }
    ],
    series: [
      {
        name: '本期',
        type: 'bar',
        tooltip: {
          valueFormatter: function (value) {
            return value
          }
        },
        data: thisEnergyList
      },
      {
        name: '同期',
        type: 'bar',
        tooltip: {
          valueFormatter: function (value) {
            return value
          }
        },
        data: lastEnergyList
      },
      {
        name: '同比',
        type: 'line',
        yAxisIndex: 1,
        tooltip: {
          valueFormatter: function (value) {
            return value
          }
        },
        data: compareList.value
      }
    ]
  }
  option && myChart.value.setOption(option)
}
// table
const tableData = ref([])
// 异步请求
const getContrastFun = async (data) => {
  const datas = {
    treeNodeId: '326745fb596d4b82a00434c0bc7b2757',
    beginCollectTime: '2024-02-01 00:00:00',
    endCollectTime: '2024-02-29 24:00:00',
    type: '',
    name: 'day',
    energyType: 1,
    ont: 'y',
    time: 'time',
    beginCollectTime1: '2024-01-01 00:00:00',
    endCollectTime1: '2024-01-31 24:00:00'
  }
  const res = await getContrast(data)
  console.log(res)
  tableData.value = res.data
  changeEchartsFun(res.data, typeChart.value)
}
const getTopologyTree = async () => {
  const { code, rows } = await topologyTree({
    energyType: activeF.value,
    topologyId: activeS.value
  })
  if (code !== 200) return
  dataL.value.treeVal = rows
  treeId.value = rows[0].id
  const nowData = getTodayFormatted()
  const sData2 = adjustDateByTypeFinal(nowData, typeChart.value)
  const datas = {
    treeNodeId: rows[0].id,
    beginCollectTime: nowData,
    endCollectTime: nowData,
    type: 'tong',
    name: 'day',
    energyType: 1,
    ont: 'y',
    time: 'time',
    beginCollectTime1: sData2,
    endCollectTime1: sData2
  }
  const data = {
    treeNodeId: '326745fb596d4b82a00434c0bc7b2757',
    beginCollectTime: '2024-02-01 00:00:00',
    endCollectTime: '2024-02-29 24:00:00',
    type: '',
    name: 'day',
    energyType: 1,
    ont: 'y',
    time: 'time',
    beginCollectTime1: '2024-01-01 00:00:00',
    endCollectTime1: '2024-01-31 24:00:00'
  }
  getContrastFun(data)
}
const getTopologymenu = async () => {
  const { code, rows } = await topologymenu({ menuId: 11 })
  if (code !== 200) return
  dataL.value.secondLevel = rows
  activeS.value = rows[0].topologyId
  getTopologyTree()
}
const getEnergyType = async () => {
  const { code, rows } = await energyType({})
  if (code !== 200) return
  getTopologymenu()
  dataL.value.firstOrder = rows
  activeF.value = rows[0].energyType
}
onMounted(() => {
  setUpEcharts()
  getEnergyType()
})
</script>

<template>
  <div class="test">
    <div class="testL">
      <el-scrollbar>
        <!-- 类别 -->
        <div class="LFirst">
          <div class="LFtitle">类别:</div>
          <div class="LFvalue Lvalue">
            <div
              v-for="item in dataL.firstOrder"
              :key="item.energyType"
              class="LFitem Litem"
              :class="{ active: item.energyType === activeF }"
              @click="firstClick(item.energyType)"
            >
              {{ item.energyName }}
            </div>
          </div>
        </div>
        <!-- 标签 -->
        <div class="LFirst">
          <div class="LFtitle">标签:</div>
          <div class="LFvalue Lvalue">
            <div
              v-for="item in dataL.secondLevel"
              :key="item.topologyId"
              class="LFitem Litem"
              :class="{ active: item.topologyId === activeS }"
              @click="secondClick(item.topologyId)"
            >
              {{ item.topologyName }}
            </div>
          </div>
        </div>
        <hr />
        <div class="LTree">
          <div class="Linput">
            <el-input v-model="filterText" style="width: 100%" placeholder="筛选关键字" />
          </div>
          <el-tree
            ref="treeRef"
            :data="dataL.treeVal"
            :props="defaultProps"
            @node-click="handleNodeClick"
            default-expand-all
            :filter-node-method="filterNode"
          />
        </div>
      </el-scrollbar>
    </div>
    <div class="testR">
      <el-scrollbar>
        <div class="rTop">
          <div class="rForm">
            <el-form :inline="true" :model="formInline" class="demo-form-inline">
              <el-form-item label="时间范围" style="width: 40%">
                <el-date-picker
                  v-model="formInline.startTime"
                  :type="dateType"
                  range-separator="至"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                />
              </el-form-item>
              <el-form-item style="width: 10%">
                <div class="tabT">
                  <div
                    class="tabTY tadTc"
                    :class="{ activeT: dateType === 'yearrange' }"
                    @click="changeType('yearrange')"
                  >
                    年
                  </div>
                  <div
                    class="tabTM tadTc"
                    :class="{ activeT: dateType === 'monthrange' }"
                    @click="changeType('monthrange')"
                  >
                    月
                  </div>
                  <div
                    class="tabTD tadTc"
                    :class="{ activeT: dateType === 'daterange' }"
                    @click="changeType('daterange')"
                  >
                    日
                  </div>
                </div>
              </el-form-item>
              <el-form-item style="width: 10%">
                <div class="tabT">
                  <div
                    class="tabTY tadTcT"
                    :class="{ activeT: typeChart === 0 }"
                    @click="changeTypeChart(0)"
                  >
                    同比
                  </div>
                  <div
                    class="tabTM tadTcT"
                    :class="{ activeT: typeChart === 1 }"
                    @click="changeTypeChart(1)"
                  >
                    环比
                  </div>
                </div>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="onSubmit">查询</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
        <div class="rCenter">
          <div class="mainE"></div>
        </div>
        <div class="rBottom">
          <div class="rTable">
            <el-table :data="tableData" border style="width: 100%">
              <el-table-column prop="treeNodeName" label="节点" width="180" />
              <el-table-column prop="time" label="时间" width="180" />
              <el-table-column label="本期" align="center">
                <el-table-column prop="thisEnergy" label="能耗/KWH" />
                <el-table-column prop="thisBiaomei" label="标煤/吨" />
              </el-table-column>
              <el-table-column label="同期" align="center">
                <el-table-column prop="lastEnergy" label="能耗/KWH" />
                <el-table-column prop="lastBiaomei" label="标煤/吨" />
              </el-table-column>
              <el-table-column prop="compare" label="环比" />
            </el-table>
          </div>
        </div>
      </el-scrollbar>
    </div>
  </div>
</template>

<style scoped lang="scss">
div {
  box-sizing: border-box;
}
.test {
  display: flex;
  justify-content: space-between;
  width: 100vw;
  height: 100vh;
  background: #efefef;
  .testL {
    padding: 20px;
    width: 17%;
    height: 100%;
    font-size: 14px;
    background: #fff;
    .LFirst {
      display: flex;
      .LFtitle {
        width: 55px;
      }
      .LFvalue {
        flex: 1;
        display: flex;
        flex-wrap: wrap;
        .LFitem {
          margin: 0 10px;
          margin-bottom: 10px;
          padding: 3px 15px;
          border-radius: 5px;
          background: #d7d7d7;
          cursor: pointer;
        }
        .active {
          background: #6699ff;
        }
      }
    }
    .Linput {
      margin-top: 10px;
      margin-bottom: 10px;
      width: 100%;
    }
  }
  .testR {
    padding: 20px;
    width: 82.5%;
    height: 100%;
    background: #fff;
    .rTop {
      width: 100%;
      height: 20%;
      .tabT {
        display: flex;
        justify-content: space-around;
        width: 100%;
        .tadTc {
          width: 30%;
          text-align: center;
          border-radius: 5px;
          background: #dcdfe6;
          cursor: pointer;
        }
        .tadTcT {
          width: 35%;
          text-align: center;
          border-radius: 5px;
          background: #dcdfe6;
          cursor: pointer;
        }
        .activeT {
          background: #1890ff;
          color: #fff;
        }
      }
    }
    .rCenter {
      width: 100%;
      height: 50vh;
      .mainE {
        width: 100%;
        height: 100%;
      }
    }
    .rBottom {
      width: 100%;
      height: 40%;
    }
  }
}
.el-tree {
  background-color: transparent;
}
</style>
